package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.FittingUsed;
import com.isunland.managesystem.entity.MaterielLomContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/2/23 15:03
 */
public class FittingUsedDatailFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.FittingUsedDatailFragment.EXTRA_CONTENT";
  protected static final String EXTRA_DEALID =
      "com.isunland.managesystem.ui.FittingUsedDatailFragment.EXTRA_DEALID";

  private final int CHOOSE_KIND = 0;//配件类型
  private final int CHOOSE_MATERIE = 1;//配件名

  @BindView(R.id.tv_fittingType) TextView tvFittingType;
  @BindView(R.id.et_fittingName) EditText etFittingName;
  @BindView(R.id.et_useNum) EditText etUseNum;
  @BindView(R.id.et_unitPrice) EditText etUnitPrice;
  @BindView(R.id.et_totalCosts) EditText etTotalCosts;
  @BindView(R.id.et_remark) EditText etRemark;
  private FittingUsed mContent;
  private String mDealId;
  private BaseVolleyActivity mActivity;
  private String materialKindName;
  private String materialKindCode;
  private String materialName;
  private String materialId;
  private String mMainStatus;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setTitle(R.string.fittingUsed);
    }
    mContent = (FittingUsed) getArguments().getSerializable(EXTRA_CONTENT);
    mDealId = getArguments().getString(EXTRA_DEALID);
    mMainStatus = getArguments().getString(CustomerProblemListFragment.EXTRA_MAINSTATUS);

    if (mContent == null) {
      //添加
      materialKindName = "";
      materialKindCode = "";
      materialName = "";
      materialId = "";
    } else {
      //详情
      materialKindName = mContent.getMaterialKindName();
      materialKindCode = mContent.getMaterialKindCode();
      materialName = mContent.getMaterialName();
      materialId = mContent.getMaterialId();
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_fitting_used, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    if (mContent != null) {
      tvFittingType.setText(mContent.getMaterialKindName());
      etFittingName.setText(mContent.getMaterialName());
      etUseNum.setText(mContent.getUseNum());
      etUnitPrice.setText(mContent.getUnitPrice());
      etTotalCosts.setText(mContent.getSumPrice());
      etRemark.setText(mContent.getRemark());
    } else {
      etUseNum.setText("0");
      etUnitPrice.setText("0.0");
      etTotalCosts.setText("0.0");
    }
    etUseNum.addTextChangedListener(myWatcher());
    etUnitPrice.addTextChangedListener(myWatcher());
    etFittingName.addTextChangedListener(myWatcher());
    if (DataStatus.DEALED.equalsIgnoreCase(mMainStatus) || DataStatus.VISITED.equalsIgnoreCase(
        mMainStatus)) {
      tvFittingType.setEnabled(false);
      etFittingName.setEnabled(false);
      etUseNum.setEnabled(false);
      etUnitPrice.setEnabled(false);
      etTotalCosts.setEnabled(false);
      etRemark.setEnabled(false);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //主记录是待处理或处理中才可以保存删除
    if (DataStatus.UNDEAL.equalsIgnoreCase(mMainStatus) || DataStatus.DEALING.equalsIgnoreCase(
        mMainStatus)) {
      inflater.inflate(R.menu.menu_save_delete, menu);
      if (mContent == null) {
        //添加只有保存
        menu.getItem(1).setVisible(false);
      }
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_save:
        if (!TextUtils.isEmpty(tvFittingType.getText().toString()) && !TextUtils.isEmpty(
            etFittingName.getText().toString())) {
          volleyPostSave();
        } else {
          ToastUtil.show(R.string.notComplete);
        }
        return true;
      case R.id.menu_item_delete:
        volleyPostDel();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FITTING_USED_SAVE);
    HashMap<String, String> item = new HashMap<>();

    if (mContent != null) {
      item.put("id", mContent.getId());
    }
    item.put("faultDealId", mDealId);
    item.put("materialKindName", materialKindName);
    item.put("materialKindCode", materialKindCode);
    item.put("materialName", etFittingName.getText().toString());
    item.put("materialId", materialId);
    item.put("useNum", etUseNum.getText().toString());
    item.put("unitPrice", etUnitPrice.getText().toString());
    item.put("sumPrice", etTotalCosts.getText().toString());
    item.put("remark", etRemark.getText().toString());
    HashMap<String, String> params = new HashMap<>();
    params.put("json", new JSONObject(item).toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostDel() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FITTING_USED_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  @OnClick({ R.id.tv_fittingType, R.id.et_fittingName }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_fittingType:
        //配件类型
        showDialog(CHOOSE_KIND);
        break;
      case R.id.et_fittingName:
        //配件名称
        if (TextUtils.isEmpty(tvFittingType.getText().toString())) {
          ToastUtil.show(R.string.choose_kind);
        } else {
          showDialog(CHOOSE_MATERIE);
        }
        break;
    }
  }

  protected void showDialog(int requestCode) {

    DialogFragment dialog = null;
    switch (requestCode) {

      //选择配件类别
      case CHOOSE_KIND:
        dialog = new MaterielDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("type", MaterielDialogFragment.type_catragory);
        bundle.putSerializable("customerId", "");
        bundle.putSerializable("storageId", "");
        bundle.putSerializable("kindId", "");
        dialog.setArguments(bundle);
        break;
      //选择配件名称
      case CHOOSE_MATERIE:

        dialog = new MaterielDialogFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putSerializable("type", MaterielDialogFragment.type_materiel);
        bundle2.putSerializable("customerId", "");
        bundle2.putSerializable("storageId", "");
        bundle2.putSerializable("kindId", materialKindCode);
        dialog.setArguments(bundle2);
        break;

      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    assert dialog != null;
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  protected TextWatcher myWatcher() {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

        try {
          materialId = "";
          double useNum = 0;// 使用数量
          double unitPrice = 0.0;//单价
          double sumPrice;//合计
          if (!TextUtils.isEmpty(etUseNum.getText().toString())) {
            useNum = Double.parseDouble(etUseNum.getText().toString());
          }
          if (!TextUtils.isEmpty(etUnitPrice.getText().toString())) {
            unitPrice = Double.parseDouble(etUnitPrice.getText().toString());
          }
          sumPrice = useNum * unitPrice;
          etTotalCosts.setText(String.format("%s", sumPrice));
        } catch (NumberFormatException e) {
          e.printStackTrace();
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHOOSE_KIND) {
      MaterielLomContent content =
          (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      tvFittingType.setText(content.getName());
      materialKindCode = content.getId();
      materialKindName = content.getName();
    }
    if (requestCode == CHOOSE_MATERIE) {
      MaterielLomContent content =
          (MaterielLomContent) data.getSerializableExtra(MaterielDialogFragment.EXTRA_VALUE);
      etFittingName.setText(content.getName());
      materialId = content.getId();
      materialName = content.getName();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static FittingUsedDatailFragment newInstance(FittingUsed content, String dealId,
      String mainStatus) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putString(EXTRA_DEALID, dealId);
    args.putString(CustomerProblemListFragment.EXTRA_MAINSTATUS, mainStatus);
    FittingUsedDatailFragment fragment = new FittingUsedDatailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
